#include <Timer.h>
#include "printf.h"

typedef nx_struct flashLogEntry_t 
	{
    	nx_uint16_t timeStamp;
    	nx_uint16_t temperature;
    	nx_uint8_t nodeID;
    	nx_uint8_t sentStatus;
  	} flashLogEntry_t;


module EasyDisseminationC {
	uses interface Boot;
	uses interface SplitControl as RadioControl;
	uses interface StdControl as DisseminationControl;
	uses interface DisseminationValue<flashLogEntry_t> as Value;
	
    //uses interface DisseminationValue<uint16_t> as Value;
	
    uses interface DisseminationUpdate<flashLogEntry_t> as Update;
	
    //uses interface DisseminationUpdate<uint16_t> as Update;
	
    uses interface Leds;
	uses interface Timer<TMilli>;
}

implementation {

    /* Data logging variables */
	    flashLogEntry_t m_localEntry;
    
	uint16_t counter;
	task void ShowCounter() {
    	counter = m_localEntry.temperature;
		if(counter & 0x01) call Leds.led0On(); else call Leds.led0Off();
		if(counter &0x02) call Leds.led1On(); else call Leds.led1Off();
		if(counter & 0x04) call Leds.led2On(); else call Leds.led2Off();
	}
	event void Boot.booted() {
		call RadioControl.start();
	}
	event void RadioControl.startDone(error_t err) {
		if(err != SUCCESS) call RadioControl.start();
		else {
			call DisseminationControl.start();
			m_localEntry.temperature=5;
			m_localEntry.nodeID=5;
			if ( TOS_NODE_ID == 1) call Timer.startPeriodic(200);
		}
	}
	event void RadioControl.stopDone(error_t err) {}
	event void Timer.fired() {
		m_localEntry.temperature = m_localEntry.temperature + 5;
		post ShowCounter();
		call Update.change(&m_localEntry);
	}
	event void Value.changed() {
		const flashLogEntry_t *new_value = call Value.get();
		//const uint16_t *new_value = call Value.get();
		post ShowCounter();
        printf("Non-root-node with ID = %d seeing value changed = %d\n", (new_value)->nodeID, (new_value)->temperature);
		printfflush();
	}
}
